from asyncio.windows_events import NULL
import pygame
import random
import os
from settings import *
from player import Player
from object import *

my_set = Settings()  # 用的是设置类  系统外观设置
player_images = ['../graphics/player/player_crash.png',  '../graphics/player/player_down.png','../graphics/player/player_up.png',
                 '../graphics/player/player_left.png', '../graphics/player/player_right.png', ] 
object_flag = [0,0,0,0]

white = (255, 255, 255)
black = (0, 0, 0)
gray = (128, 128, 128)
red = (200, 0, 0)
green = (0, 200, 0)
bright_red = (255, 0, 0)
bright_green = (0, 255, 0)
blue = (0, 0, 255)
start_time = 0
pause = False
# 初始化
pygame.init()
pygame.mixer.init()
# 游戏窗口初始化
window = pygame.display.set_mode(
    (my_set.screen_width, my_set.screen_height))  # 窗口大小
screen = pygame.display.get_surface()
# 设置logo和界面标题
game_icon = pygame.image.load('../graphics/changbao.png')
pygame.display.set_icon(game_icon)
pygame.display.set_caption(my_set.name)
background_image = pygame.image.load('../graphics/background.jpg').convert_alpha()
pygame.display.set_caption(my_set.name)  # 窗口名字
clock = pygame.time.Clock()  # 帧率显示,先定义一个时间对象


def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()


def button(msg, x, y, w, h, ic, ac, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    if x + w > mouse[0] > x and y + h > mouse[1] > y:
        pygame.draw.rect(window, ac, (x, y, w, h))
        if click[0] == 1 and action != None:
            action()
    else:
        pygame.draw.rect(window, ic, (x, y, w, h))
    smallText = pygame.font.SysFont('comicsansms', 20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ((x+(w/2)), (y+(h/2)))
    window.blit(textSurf, textRect)
    if msg == "Play Again":
        global start_time
        start_time = pygame.time.get_ticks()
    elif msg == "| |":
        global pause
        pause = True


def game_intro():
    global pause
    pause = False
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        window.fill(white)
        largeText = pygame.font.SysFont('comicsansms', 50)
        TextSurf, TextRect = text_objects('Esophagus adventure', largeText)
        TextRect.center = ((my_set.screen_width/2), (my_set.screen_height/2))
        window.blit(TextSurf, TextRect)
        button("GO", 120, 450, 100, 50, green, bright_green, game_loop)
        button("Quit", 420, 450, 100, 50, red, bright_red, quitgame)
        pygame.display.update()
        clock.tick(15)


def quitgame():
    pygame.quit()
    quit()


def game_loop():
    global start_time
    ObjectFlag_group = pygame.sprite.Group()  # 创建sprite容器  障碍物
    # 添加障碍物或金币创建自定义事件
    AddEnemy = pygame.USEREVENT + 1
    pygame.time.set_timer(AddEnemy, 40)
    # 音乐
    # pygame.mixer.muisc.load('bg_music.mp3')
    player = Player(1)  # 创建主角
    # 左上角计算分数
    countObj = pygame.font.Font(None, 60)
    # countObj.set_bold(True)  #加粗
    textObj = countObj.render('SCORE:0', True, (255, 0, 0))
    textRectObj = textObj.get_rect()
    # 计算分数
    count_num = 0
    # 计算碰撞次数，10次场景加一次速度，最多叠加10次
    hit_count = 0
    # 显示当前速度
    speedObj = pygame.font.Font(None, 40)
    speed_text = speedObj.render('SPEED:1', True, (255, 0, 0))
    speedRectObj = speed_text.get_rect()
    speedRectObj.top = 60
    # 加载终点
    des = Destination()
    des.load('../graphics/destination/des.png', 2, 2)
    # 运行游戏
    while True:
        # 先加载背景图
        clock.tick(60)
        window.fill(my_set.bg_color)  # 填充，参数填写的是rgb值
        window.blit(background_image,(0,0))
        ret = pygame.event.get()  # 事件
        # 退出游戏判断
        for obj in ret:
            if obj.type == pygame.QUIT:
                print('关闭窗口')
                exit()
        # 获取键盘状态
        pressed_keys = pygame.key.get_pressed()
        # 调用方法更新
        player.update(pressed_keys)
        ticks = pygame.time.get_ticks() - start_time
        if ticks > 10000:
            des.update(screen,)
            if pygame.sprite.collide_rect(player, des):
                ending('You Win!', 'Next Level')
        # 判断事件，生成场景
        for event in pygame.event.get():
            obspeed = random.randint(1, 2)
            if event.type == AddEnemy:
                if random.randint(1, 10) % 2:
                    ObjectFlag_group.add(ObjectClass(obspeed, 1))
                else:
                    ObjectFlag_group.add(ObjectClass(obspeed, 0))
        # 判断障碍物或金币碰撞
        hit = pygame.sprite.spritecollide(player, ObjectFlag_group, False)
        if hit:
            if hit[0].type == 'obstacle':
                count_num -= 50
                hit_count += 1
                hit[0].kill()
                player.image = pygame.image.load(player_images[0]).convert_alpha()
            else:
                count_num += 10
                hit_count += 1
                hit[0].kill()
        # 判断累计碰撞次数：
        if -20 <= count_num <= 30:
            player.speed = 1
        elif count_num > 30 and count_num <= 160:
            # for obj in ObjectFlag_group:
            #     obj.speed = count_num / 10
            player.speed = count_num / 30
        elif count_num >= 160:
            for obj in ObjectFlag_group:
                obj.speed = 8
            player.speed = 8
        else:
            ending('You Failed!', 'Quit')
        # 场景动画更新
        ObjectFlag_group.update()
        object_updates = ObjectFlag_group.draw(window)
        pygame.display.update(object_updates)
        # 显示角色卡片
        for object_generation in ObjectFlag_group:
            if object_flag[object_generation.obstaclenum] == 0 and object_generation.rect.top < my_set.screen_height/2 :
                show_charactercard(object_generation)
                object_flag[object_generation.obstaclenum] = 1
        # 添加画面以及帧率
        button("| |", 600, 20, 30, 40, green, black, paused)
        window.blit(player.image, player.rect)  # 添加小人画面
        textObj = countObj.render('SCORE:%d' %
                                  count_num, False, (255, 0, 0))  # 显示得分内容
        textRectObj = textObj.get_rect()
        window.blit(textObj, textRectObj)  # 这是得分
        speed_text = speedObj.render(
            'SPEED:%d' % player.speed, True, (255, 0, 0))  # 显示速度内容
        speedRectObj = speed_text.get_rect()
        speedRectObj.top = 60
        window.blit(speed_text, speedRectObj)  # 显示速度
        pygame.display.update()  # 必须要更新显示的内容

def show_charactercard(object_generation):
    waiting = True
    waited_time = pygame.time.get_ticks()
    while waiting:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        # window.fill(white)
        largeText = pygame.font.SysFont('comicsansms', 20)
        TextSurf, TextRect = text_objects(object_generation.name, largeText)
        TextRect.center = (object_generation.rect.left+(object_generation.rect.width/2), (my_set.screen_height/2)-object_generation.rect.height/4)
        window.blit(TextSurf, TextRect)
        pygame.display.update()
        clock.tick(15)
        if pygame.time.get_ticks() - waited_time > 2000:
            waiting = False



def unpause():
    global pause
    pause = False


def paused():
    while pause:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        window.fill(white)
        largeText = pygame.font.SysFont('comicsansms', 80)
        TextSurf, TextRect = text_objects('Paused', largeText)
        TextRect.center = ((my_set.screen_width/2), (my_set.screen_height/2))
        window.blit(TextSurf, TextRect)

        button("Continue", 120, 460, 100, 50, green, bright_green, unpause)
        button("Quit", 420, 460, 100, 50, red, bright_red, quitgame)
        pygame.display.update()
        clock.tick(15)

def nextlevel():
    pygame.quit()
    os.system("cd ../../level_3/mainpy & python main.py")
    quit()

def ending(result_text, button_choice):
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        window.fill(white)
        largeText = pygame.font.SysFont('comicsansms', 80)
        TextSurf, TextRect = text_objects(result_text, largeText)
        TextRect.center = ((my_set.screen_width/2), (my_set.screen_height/2))
        window.blit(TextSurf, TextRect)
        button("Play Again", 120, 460, 100, 50, green, bright_green, game_loop)
        if button_choice == 'Next Level':
            button(button_choice, 420, 460, 100, 50, red, bright_red, nextlevel)
        else:
            button(button_choice, 420, 460, 100, 50, red, bright_red, quitgame)
        pygame.display.update()
        clock.tick(15)


if __name__ == '__main__':
    game_intro()
    game_loop()
    quitgame()
